package cn.redragon.soa.controller;

import com.digibridge.common.core.brand.Brand;
import com.digibridge.common.core.web.ResponseDTO;
import com.digibridge.loyalty.stock.dto.ProductDTO;
import com.digibridge.loyalty.stock.dto.StockDTO;
import com.digibridge.loyalty.stock.dto.StockTotalDTO;
import com.digibridge.loyalty.stock.service.StockService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v2/{brand}/stock")
@Tag(name = "Stock V2 API")
@Slf4j
@RequiredArgsConstructor
@Validated
public class StockV2Controller {

    private final StockService stockService;

    @PostMapping
    @Operation(summary= "Get available stocks")
    @PreAuthorize("hasAuthority(#brand + ':STOCK:RW')")
    public ResponseDTO<StockTotalDTO> getStocks(@PathVariable Brand brand, @RequestBody @Valid List<ProductDTO> productDTOs) {
        Map<String, StockDTO> stocks = stockService.getStocksMap(brand.name(), productDTOs);
        long available = stocks.values().stream().mapToLong(StockDTO::getAvailable).sum();
        long total = stocks.values().stream().mapToLong(StockDTO::getTotal).sum();
        StockTotalDTO totalStock = StockTotalDTO.builder().stockMap(stocks).available(available).total(total).build();
        return ResponseDTO.success(totalStock);
    }
}
